using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using EPiServer.Core;
using EPiServer.DataAbstraction;
using System.Linq;

namespace OpenWaves.ActivityFeed.EPiServer
{
    public static class CategoryExtensions
    {
        public static IEnumerable<Topic> AsTopics(this CategoryList categories, string keySeparator = "/")
        {
            return categories.Select(c => Category.Find(c).AsTopic(keySeparator));
        }

        public static IEnumerable<Topic> AsHierarchicalTopics(this CategoryList categories)
        {
            return categories.SelectMany(c => Category.Find(c).AsTopicHierarchy());
        }

        public static Topic AsTopic(this Category category, string keySeparator = "/")
        {
            Contract.Requires<ArgumentNullException>(category != null);

            return new Topic("EPiServerCategory" + keySeparator + category.ID);
        }

        public static IEnumerable<Topic> AsTopicHierarchy(this Category category)
        {
            Contract.Requires<ArgumentNullException>(category != null);

            while (category != null)
            {
                yield return category.AsTopic();
                category = category.Parent;
            }
        }
    }
}